package cn.tedu.ykmall.admin.commodity.webapi.repository.impl;

import cn.tedu.ykmall.admin.commodity.webapi.repository.ICategoryCacheRepository;
import cn.tedu.ykmall.pojo.commodity.vo.AdminCategoryDetailsVO;
import cn.tedu.ykmall.pojo.commodity.vo.AdminCategorySimpleListItemVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

//组件注解，存储数据
@Repository
public class CategoryCacheRepositoryImpl implements ICategoryCacheRepository {
    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    @Override
    public Boolean exists(Long id) {
        String key = KEY_CATEGORY_ITEM_PREFIX + id;
        return redisTemplate.hasKey(key);
    }

    @Override
    public void savaEmptyValue(Long id) {
        String key = KEY_CATEGORY_ITEM_PREFIX + id;
        redisTemplate.opsForValue().set(key,null,30, TimeUnit.MINUTES);
    }

    @Override
    public void save(List<AdminCategoryDetailsVO> categories) {
        for (AdminCategoryDetailsVO category : categories){
            redisTemplate.opsForList().rightPush(KEY_CATEGORY_LIST,category);
        }
    }

    @Override
    public void save(AdminCategoryDetailsVO category) {
        String key = KEY_CATEGORY_ITEM_PREFIX + category.getId();
        redisTemplate.opsForValue().set(key,category);
    }


    @Override
    public Boolean deleteList() {
        return redisTemplate.delete(KEY_CATEGORY_LIST);
    }

    @Override
    public void deleteAllItem() {
        Set<String> keys = redisTemplate.keys(KEY_CATEGORY_ITEM_PREFIX + "*");
        redisTemplate.delete(keys);
    }

    @Override
    public AdminCategorySimpleListItemVO getCategoryById(Long id) {
        String key = KEY_CATEGORY_ITEM_PREFIX+id;
        Serializable serializable = redisTemplate.opsForValue().get(key);
        if(serializable != null){
            AdminCategorySimpleListItemVO category = (AdminCategorySimpleListItemVO) serializable;
            return category;
        }
        return null;
    }

}
